﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Fleck;
using Newtonsoft.Json;
using Quartz;
using WebSocketDemo.Tools;

namespace WebSocketDemo.Job
{
    public class PushMessageJob : IJob
    {
        private SqlService sqlService = new SqlService();
        void IJob.Execute(IJobExecutionContext context)
        {
            var ws = WebSocketHelper.GetInstance();
            while (true)
            {
                ws.SendMsg(new MessageModel { MessageContent = $"Ticks:{DateTime.Now.Ticks}", Type = 1 });

                Thread.Sleep(2000);
            }
            //var messages = sqlService.GetMessages();
            //WriteMessage($"执行时间：{DateTime.Now:yyyy-MM-dd HH:mm:ss};消息数量：{messages.Count};第一条消息ID：{messages.FirstOrDefault()?.Id}");
            //Console.WriteLine($"执行时间：{DateTime.Now:yyyy-MM-dd HH:mm:ss};消息数量：{messages.Count};第一条消息ID：{messages.FirstOrDefault()?.Id}");
            //foreach (var message in messages)
            //{
            //    ws.SendMsg(message.Text);
            //}
        }

        /// <summary>
        /// 输出指定信息到文本文件
        /// </summary>
        /// <param name="msg">输出信息</param>
        /// <param name="path">文本文件路径</param>
        public void WriteMessage(string msg, string path = "")
        {
            if (string.IsNullOrEmpty(path))
            {
                var virtualPath = "/LogFiles/";
                var directory = $"{AppDomain.CurrentDomain.BaseDirectory}{virtualPath}";
                if (!Directory.Exists(directory))
                {
                    Directory.CreateDirectory(directory);
                }

                path = $"{directory}log{DateTime.Now:yyyyMMdd}.txt";
            }
            using (FileStream fs = new FileStream(path, FileMode.OpenOrCreate, FileAccess.Write))
            {
                using (StreamWriter sw = new StreamWriter(fs))
                {
                    sw.BaseStream.Seek(0, SeekOrigin.End);
                    sw.WriteLine("{0}\n", msg, DateTime.Now);
                    sw.Flush();
                }
            }
        }
    }
}
